package com.jhxy.algorithm.majorityelement;

import java.util.HashMap;

/**
 * Date: 2024/3/10 15:16
 * Author: T_log
 * Description: 多数元素_暴力——哈希+随机法
 */
public class MajorityElement {


    public int majorityElement(int[] nums) {
        HashMap<Integer,Integer> map = new HashMap<>();
        for (Integer num :nums) {
            if (map.containsKey(num)) {
                map.put(num,map.get(num) + 1);
            }else {
                map.put(num,1);
            }
        }

        //遍历hash，找到最大value对应的最大key

        //出现的次数
        int cnt =  Integer.MIN_VALUE;
        int maxNum = nums[0];

        for (int num : map.keySet()) {
            if (cnt < map.get(num)) {
                maxNum = num;
                cnt = map.get(num);
            }
        }

        return maxNum;
    }

}
